package com.njtoyo.taxi.admin.service.marketing.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.google.common.collect.Lists;
import com.njtoyo.taxi.admin.library.Const;
import com.njtoyo.taxi.admin.library.common.util.CopyUtil;
import com.njtoyo.taxi.admin.library.taxi_service.SkillPrizedService;
import com.njtoyo.taxi.admin.mapper.master.entity.ActivityPrized;
import com.njtoyo.taxi.admin.mapper.master.entity.ActivitySeckillAward;
import com.njtoyo.taxi.admin.mapper.master.entity.ActivitySeckillPrize;
import com.njtoyo.taxi.admin.mapper.master.enums.ActivityPrizedCategory;
import com.njtoyo.taxi.admin.mapper.master.mapper.ActivityPrizedMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.ActivitySeckillAwardMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.ActivitySeckillPrizeMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.ActivitySeckillWinningPrizeMapper;
import com.njtoyo.taxi.admin.rest.presenter.marketing.seckill.AwardListPresenter;
import com.njtoyo.taxi.admin.rest.wrapper.marketing.seckill.AwardListWrapper;
import com.njtoyo.taxi.admin.rest.wrapper.marketing.seckill.CreateAwardWrapper;
import com.njtoyo.taxi.admin.rest.wrapper.marketing.seckill.UpdateAwardIsOnlineWrapper;
import com.njtoyo.taxi.admin.rest.wrapper.marketing.seckill.UpdateAwardWrapper;
import com.njtoyo.taxi.admin.service.marketing.SeckillAwardService;
import com.taxi.entity.common.RestResult;
import com.taxi.entity.common.ResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Component
@DS(Const.PRIMARY_DS)
public class SeckillAwardServiceImpl implements SeckillAwardService {

    @Autowired
    private ActivityPrizedMapper activityPrizedMapper;

    @Autowired
    private ActivitySeckillAwardMapper activitySeckillAwardMapper;

    @Autowired
    private ActivitySeckillWinningPrizeMapper activitySeckillWinningPrizeMapper;

    @Autowired
    private ActivitySeckillPrizeMapper activitySeckillPrizeMapper;

    @Autowired
    private SkillPrizedService skillPrizedService;

    @Override
    public RestResult getList(Long activityId, AwardListWrapper wrapper) {
        ActivityPrized seckill = activityPrizedMapper.getActivityById(ActivityPrizedCategory.seckill, activityId);
        if (Objects.isNull(seckill)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }
        wrapper.setActivityId(activityId);
        wrapper.setOrders(Lists.newArrayList(new OrderItem("id", false)));
        IPage<AwardListPresenter> res = activitySeckillAwardMapper.selectPage(wrapper);

        return RestResult.success(res);
    }

    @Override
    @Transactional
    public RestResult delete(Long activityId, Long awardId) {
        ActivityPrized seckill = activityPrizedMapper.getActivityById(ActivityPrizedCategory.seckill, activityId);
        if (Objects.isNull(seckill)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }

        QueryWrapper<ActivitySeckillAward> awardQueryWrapper = new QueryWrapper<>();
        awardQueryWrapper.eq("id", awardId).eq("activity_id", activityId);
        ActivitySeckillAward award = activitySeckillAwardMapper.selectOne(awardQueryWrapper);
        if (Objects.isNull(award)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }
        if (activitySeckillWinningPrizeMapper.selectCountByAwardId(awardId) > 0) {
            return RestResult.failed("奖项下已存在中奖记录，不可删除");
        }
        if (award.getIsOnline() && !seckill.getIsOfflineUpdate()) {
            return RestResult.failed("需要将活动下线后再删除");
        }
        // 删除
        activitySeckillAwardMapper.delete(awardQueryWrapper);
        QueryWrapper<ActivitySeckillPrize> prizeQueryWrapper = new QueryWrapper<>();
        prizeQueryWrapper.eq("activity_id", activityId).eq("activity_award_id", awardId);
        activitySeckillPrizeMapper.delete(prizeQueryWrapper);

        // 清除缓存
        skillPrizedService.resetAward();

        return RestResult.success();
    }

    @Override
    public RestResult create(CreateAwardWrapper createAwardWrapper) {
        // 校验秒杀活动是否存在
        ActivityPrized seckill = activityPrizedMapper.getActivityById(ActivityPrizedCategory.seckill, createAwardWrapper.getActivityId());
        if (Objects.isNull(seckill)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }

        if (!createAwardWrapper.getIsCoverAllRegions() && Objects.isNull(createAwardWrapper.getRegionId())) {
            return RestResult.failed("需设置区域编号");
        }

        // 判断是否已经存在奖项（同地区的规则只能存在一个，全地区性质的规则也只能存在一个）
        QueryWrapper<ActivitySeckillAward> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("activity_id", createAwardWrapper.getActivityId())
                .eq("is_cover_all_regions", createAwardWrapper.getIsCoverAllRegions())
                .eq(!createAwardWrapper.getIsCoverAllRegions() && Objects.nonNull(createAwardWrapper.getRegionId()), "region_id", createAwardWrapper.getRegionId());

        Integer awardCount = activitySeckillAwardMapper.selectCount(queryWrapper);

        if (awardCount > 0) {
            return RestResult.failed("已存在相同奖项");
        }

        ActivitySeckillAward insert = CopyUtil.copy(createAwardWrapper, ActivitySeckillAward.class);

        insert.setIsOnline(false);
        Integer res = activitySeckillAwardMapper.insert(insert);

        return RestResult.success(res);
    }

    @Override
    public RestResult update(Long id, UpdateAwardWrapper updateAwardWrapper) {
        // 校验奖项是否存在
        ActivitySeckillAward award = activitySeckillAwardMapper.selectById(id);
        if (Objects.isNull(award)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }

        // 校验秒杀活动是否存在
        ActivityPrized seckill = activityPrizedMapper.getActivityById(ActivityPrizedCategory.seckill, award.getActivityId());
        if (Objects.isNull(seckill)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }

        // 判断活动状态
        if (award.getIsOnline() && !seckill.getIsOfflineUpdate()) {
            return RestResult.failed("需要将活动下线后再修改");
        }

        // 判断是否已经存在奖项（同地区的规则只能存在一个，全地区性质的规则也只能存在一个）
        QueryWrapper<ActivitySeckillAward> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("activity_id", updateAwardWrapper.getActivityId())
                .eq("is_cover_all_regions", updateAwardWrapper.getIsCoverAllRegions())
                .eq(!updateAwardWrapper.getIsCoverAllRegions() && Objects.nonNull(updateAwardWrapper.getRegionId()), "region_id", updateAwardWrapper.getRegionId())
                .ne("id", id);

        Integer awardCount = activitySeckillAwardMapper.selectCount(queryWrapper);

        if (awardCount > 0) {
            return RestResult.failed("已存在相同奖项");
        }

        ActivitySeckillAward update = CopyUtil.copy(updateAwardWrapper, ActivitySeckillAward.class);
        update.setId(id);
        Integer res = activitySeckillAwardMapper.updateById(update);

        // 清除缓存
        skillPrizedService.resetAward();

        return RestResult.success(res);
    }

    @Override
    public RestResult updateIsOnline(Long id, UpdateAwardIsOnlineWrapper updateAwardWrapper) {
        // 判断奖项是否存在
        ActivitySeckillAward award = activitySeckillAwardMapper.selectById(id);
        if (Objects.isNull(award)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }

        boolean res = new LambdaUpdateChainWrapper<>(activitySeckillAwardMapper)
                .eq(ActivitySeckillAward::getId, id)
                .set(ActivitySeckillAward::getIsOnline, updateAwardWrapper.getIsOnline())
                .update();

        // 清除缓存
        skillPrizedService.resetAward();

        return RestResult.success(res);
    }
}
